package com.xianyv.security.exception;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.xianyv.common.Result;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AuthenticationEntryPointHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        Result<String> error = Result.error("未登入");
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        String result = new ObjectMapper().writeValueAsString(error);
        response.getWriter().write(result);
    }
}
